package com.foreveross.crawl.adapter.sub.impl20140402.v3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.adapter.PlaneInfoEntityBuilder;
import com.foreveross.crawl.common.util.RegHtmlUtil;
import com.foreveross.crawl.domain.airfreight.CabinEntity;
import com.foreveross.crawl.domain.airfreight.single.SinglePlaneInfoEntity;
import com.foreveross.crawl.enums.RouteTypeEnum;
import com.foreveross.taskservice.common.bean.TaskModel;
import com.google.common.collect.Maps;

/**
 * 20140530 目前支持 国内 国际 单程
 * 
 * @author linchuncheng (2014-08-06 luomingliang	)
 * 
 */
public class SpringtourAdapter extends AbstractAdapter {

	public SpringtourAdapter(TaskModel taskQueue) {
		super(taskQueue);
	}

	@Override
	public String getUrl() throws Exception {
		Map<String, String> p = Maps.newHashMap();
		p.put("startCity", taskQueue.getFromCity().concat("|").concat(taskQueue.getFromCityName()));
		p.put("endCity", taskQueue.getToCity().concat("|").concat(taskQueue.getToCityName()));
		p.put("startTime", taskQueue.getFlightDate());
		p.put("flightType", taskQueue.getIsReturn() + "");
		if (taskQueue.getIsReturn() == 1) p.put("endTime", taskQueue.getReturnGrabDate());
		return super.getBaseGetUrl("http://sh.springtour.com/home/Flight/Search", p);
	}

	// Html字符串转义
	private static String htmlConverter(String html) {
		return html.replaceAll("&quot;", "\"").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&nbsp;", " ").replaceAll("&amp;", "&");
	}

	@Override
	public Object fetch(String url) throws Exception {
		HttpRequestBase request = null;
		String page = null;
		try {
			request = new HttpGet(getUrl());
			page = super.excuteRequest(getHttpClient(), request, true);
			page = RegHtmlUtil.regStr(page, "data-content=\"(.*?)\"");
			page = htmlConverter(page);
		} catch (Exception e) {
			rollbackProxyIp(false);
			logger.error("数据抓取失败。 " + e.getMessage());
		} finally {
			request = null;
		}
		if (super.getRouteType() == RouteTypeEnum.DOMESTIC_ONEWAYTRIP) {
			JSONObject obj = JSONObject.fromObject(page);
			return obj;
		}
		return page;
	}

	@Override
	public boolean validateFetch(Object fetchObject) throws Exception {
		return true;
	}

	@Override
	public List<Object> paraseToVo(Object fetchObject) throws Exception {
		switch (getRouteType()) {
		case DOMESTIC_ONEWAYTRIP:
			return paraseOneWayByJson((JSONObject) fetchObject);
		}
		return null;
	}

	/**
	 * 解析国内单程，通过json
	 * 
	 * @return
	 * @throws Exception
	 */
	private List<Object> paraseOneWayByJson(JSONObject json) throws Exception {
		List<SinglePlaneInfoEntity> entitys = new ArrayList<SinglePlaneInfoEntity>();
		JSONArray flights = null;// 航班信息
		flights = json.getJSONArray("Flights");
		entitys = setEntitysInfo(flights, entitys);
		return Arrays.asList(entitys.toArray());
	}

	private List<SinglePlaneInfoEntity> setEntitysInfo(JSONArray flights, List<SinglePlaneInfoEntity> entitys) throws Exception {
		JSONObject flight = null;// 单条航班记录
		SinglePlaneInfoEntity entity = null;
		try {
			for (int i = 0; i < flights.size(); i++) {
				flight = flights.getJSONObject(i);
				entity = this.getEntitys(flight.getString("FlightNo"), entitys);
				if (entity == null) {
					double totalLowestPrice = flight.getDouble("Price");
					entity = PlaneInfoEntityBuilder.buildPlaneInfo(taskQueue, flight.getString("AirlineCode"), flight.getString("AirlineName"), flight.getString("AirlineName"), flight.getString("DepartureTime"), flight.getString("DescentTime"),
							flight.getString("FlightNo"), totalLowestPrice + "", null, null, null, null, null, null, flight.getString("AirplaneType"), SinglePlaneInfoEntity.class);
					double highestPricce = flight.getDouble("Price");
					double taxesPrice = 0.0;
					JSONArray cabinList = flight.getJSONArray("CabinList");// 全部舱位
					for (int j = 0; j < cabinList.size(); j++) {
						JSONObject cabin = cabinList.getJSONObject(j);
						String originalPrice = cabin.getDouble("AdultPrice") + cabin.getDouble("AdultFee") + "";
						taxesPrice = cabin.getDouble("AdultFee");
						double price = cabin.getDouble("AdultPrice");
						entity.getCabins().add(PlaneInfoEntityBuilder.buildCabinInfo(cabin.getString("CabinName"), cabin.getString("CabinCode"), null, taxesPrice + "", price + "", originalPrice, null, cabin.getString("Limit"), CabinEntity.class));
						if (price > highestPricce) highestPricce = price;
					}
					entity.setTotalHighestPrice(highestPricce);
					entity.setSumHighestPrice(highestPricce + taxesPrice);
					entity.setSumLowestPrice(totalLowestPrice + taxesPrice);
					entitys.add(entity);
				}
			}
		} finally {
			entity = null;
			flight = null;
		}
		return entitys;
	}

	private SinglePlaneInfoEntity getEntitys(String flightNo, List<SinglePlaneInfoEntity> entitys) {
		if (flightNo == null || entitys == null || entitys.isEmpty()) {
			return null;
		}
		for (SinglePlaneInfoEntity entity : entitys) {
			if (flightNo.equals(entity.getFlightNo())) {
				return entity;
			}
		}
		return null;
	}

}
